<!-- eslint-disable vue/no-template-shadow -->
<template>
  <div>
    <el-table
      ref="mytable"
      v-loading="loading"
      :data="tableData"
      :class="options && options.tabletype"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      border
      style="width: 100%; margin: 10px 0px"
      size="mini"
      v-bind="options.bind"
      element-loading-text="拼命加载中，请稍候......"
      :row-class-name="tableRowClassNames"
      @selection-change="selectRow"
      @current-change="CurrentChange"
      @row-click="rowClick"
    >
      <!-- 复选框 -->
      <el-table-column
        v-if="
          options && options.selection && (!options.isShow || options.isShow())
        "
        type="selection"
        width="55"
      />
      <!-- 序号 -->
      <el-table-column
        v-if="options && options.index"
        width="60"
        align="center"
        type="index"
        :label="options && options.labelIndex"
      />

      <el-table-column
        v-if="
          operates && operates.length > 0 && options && !options.iscloseoperates
        "
        v-bind="options && options.props"
        label="操作"
        :width="options && options.btnwidth ? options.btnwidth : 80"
      >
        <template slot-scope="scope">
          <div class="operates">
            <template v-for="(btn, key) in operates">
              <!--  行编辑-->
              <template
                v-if="btn.code ==='lineedit' || btn.label==='行编辑'"
              >
                <el-link
                  v-if="!showBtn[scope.$index]"
                  :key="key+1"
                  size="mini"
                  type="primary"
                  @click.native.prevent="handleEdit(scope.row, scope.$index)"
                >{{ btn.label }}</el-link>
                <el-link
                  v-if="showBtn[scope.$index]"
                  :key="key+3"
                  size="mini"
                  type="primary"
                  @click.native.prevent="handleUpdate(scope.row, scope.$index)"
                >保存</el-link>
                <el-link
                  v-if="showBtn[scope.$index]"
                  :key="key+2"
                  size="mini"
                  type="primary"
                  @click.native.prevent="btnhandleCancel(scope.row, scope.$index)"
                >取消</el-link>
              </template>

              <!-- (options && options.iszf && options[options.iszf] && options[options.iszf] === '03'?false :true) -->
              <!-- 普通按钮 -->
              <el-link
                v-else-if="tablebtnQx(scope.row, scope.$index, btn)"
                :key="key"
                :size="btn.size || 'mini'"
                :type="btn.type || `primary`"
                :icon="btn.icon"
                :plain="btn.plain"
                :style="btn.setStyle && btn.setStyle(scope.row, scope.$index)"
                v-bind="btn.props"
                :disabled="
                  btn.disabled && btn.disabled(scope.row, scope.$index)
                "
                @click.native.prevent="btn.method(scope.row, scope.$index)"
              >{{ btn.label }}</el-link>
              <el-link v-else :key="btn.label" disabled>{{
                btn.label
              }}</el-link>
            </template>
          </div>
        </template>
      </el-table-column>
      <!-- 表格数据  v-if="!column.isShow || (column.isShow && column.isShow())" -->
      <template v-for="(column, index) in columns">
        <el-table-column
          v-if="
            !column.isShow ||
              (typeof column.isShow === 'function'
                ? column.isShow(row, index)
                : !column.isShow)
          "
          :key="index"
          v-bind="column.props"
          :prop="column.prop"
          :label="column.label"
          :align="column.align"
          :width="column.width"
          :min-width="column.minwidth"
        >
          <template slot-scope="scope">
            <template v-if="!column.render">
              <!-- 自定义数据吧 -->
              <template v-if="column.formatter">
                <span
                  @click="column.click && column.click(scope.row, scope.$index)"
                  v-html="column.formatter(scope.row, column, scope.$index)"
                ></span>
              </template>
              <template v-else-if="column.newjump">
                <router-link
                  class="newjump"
                  type="primary"
                  :underline="false"
                  v-bind="{ target: '_blank', ...column.target }"
                  :to="column.newjump(scope.row, column, scope.$index)"
                >{{ scope.row[column.prop] || column.content }}</router-link>
              </template>
              <!-- 弹出框 -->
              <template v-else-if="column.popover">
                <el-popover
                  :placement="column.popover.placement || 'bottom'"
                  :width="column.popover.width || 500"
                  trigger="click"
                >
                  <slot name="popoverSlot">{{
                    scope.row[column.prop] || column.content
                  }}</slot>
                  <span
                    slot="reference"
                    :style="
                      column.click ? 'color: #409EFF; cursor: pointer;' : null
                    "
                    @click="
                      column.click && column.click(scope.row, scope.$index)
                    "
                  >
                    {{ scope.row[column.prop] || column.content }}
                    {{
                      `${
                        scope.row[column.prop] && column.unit ? column.unit : ""
                      }`
                    }}
                  </span>
                </el-popover>
              </template>
              <template v-else-if="column.optionsdic">
                <span
                  :style="
                    column.click ? 'color: #409EFF; cursor: pointer;' : null
                  "
                  @click="column.click && column.click(scope.row, scope.$index)"
                >
                  {{ dicColumnProp(scope.row, column) || column.content }}
                  <!-- {{ column.propoptionsdic }} -->
                  {{
                    `${
                      scope.row[column.prop] && column.unit ? column.unit : ""
                    }`
                  }}
                </span>
              </template>
              <!-- 没格式的数据啊啊啊啊 -->
              <template v-else>
                <span
                  :style="
                    column.click ? 'color: #409EFF; cursor: pointer;' : null
                  "
                  @click="column.click && column.click(scope.row, scope.$index)"
                >
                  {{ scope.row[column.prop] || column.content }}
                  {{
                    `${
                      scope.row[column.prop] && column.unit ? column.unit : ""
                    }`
                  }}
                </span>
              </template>
            </template>
            <template v-else>
              <render
                :column="column"
                :row="scope.row"
                :render="column.render"
                :index="index"
              />
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>
// 行编辑操作文档 https://blog.csdn.net/liaoxuewu/article/details/81184821?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-81184821-blog-116494160.235%5Ev38%5Epc_relevant_anti_t3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-81184821-blog-116494160.235%5Ev38%5Epc_relevant_anti_t3&utm_relevant_index=10
<script>
export default {
  name: "PublicTable",
  props: {
    // 单选 radio 和多选 check
    tabletype: {
      type: String,
      default: "check",
    },
    // 表格数据
    tableData: {
      type: Array,
      default() {
        return [];
      },
    },
    // 表格加载项
    loading: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 配置项
    options: {
      type: Object,
      default() {
        return {};
      },
    },
    // 操作按钮配置
    operates: {
      type: Array,
      default() {
        return [];
      },
    },
    // 操作按钮配置
    columns: {
      type: Array,
      default() {
        return [];
      },
    },
    tableRowClassName: {
      type: Function,
      default() {
        return "";
      },
    },
  },
  data() {
    return {
      // tableData: []
      list: [],
      isdic: false,
      showEdit: [], // 显示编辑框
      showBtn: [],
      showBtnOrdinary: true
    };
  },
  computed: {
    // table按钮权限
    tablebtnQx() {
      return (row, index, btn) => {
        if (btn.isShow) {
          return typeof btn.isShow === "function"
            ? btn.isShow(row, index)
            : btn.isShow;
        } else {
          if (this.options && this.options.iszf) {
            return this.isEditShow(row[this.options.iszf], row, index, btn);
          }
          return true;
        }
      };
    },
    dicColumnProp() {
      return (row, column) => {
        return row[column.prop + "dict"];
      };
    },
  },
  watch: {
    tableData: {
      deep: true,
      handler(n, o) {
        // 发生变化就去翻译一下值
        this.formAssignment();
      },
    },
  },
  mounted() {},
  methods: {
    // 点击编辑
    handleEdit(row, index) {
      this.showEdit[index] = true;
      this.showBtn[index] = true;
      this.$set(this.showEdit,row,true)
      this.$set(this.showBtn,row,true)
    },
    // 取消编辑
    handelCancel(row, index) {
      this.getContentList();
      this.showEdit[index] = false;
      this.showBtn[index] = false;
    },
    // 点击更新
    handleUpdate(formName) {

    },
    // table_index(index) {
    //   return (this.currentPage - 1) * this.pageSize + index + 1;
    // },
    rowClick(row, column, event) {
      this.$emit("row-click", row, column, event);
    },
    // 表格 自动翻译字典
    formAssignment() {
      return new Promise((resolve, reject) => {
        // 配置数组
        const arr = [];
        // 进行字典的获取
        this.columns.forEach((t) => {
          if (t.optionsdic) {
            arr.push(t.optionsdic);
          }
        });
        // 去重
        const newArr = [...new Set(arr)];
        // 生成promise 数组
        const promiseArr = [];
        newArr.forEach((t) => {
          promiseArr.push(this.$store.dispatch("dict/adddict", { diccode: t }));
        });
        // 字典赋值
        Promise.all(promiseArr).then((val) => {
          newArr.forEach((t, i) => {
            // 翻译后的value值
            this.columns.forEach((obj1) => {
              const propname = obj1.prop + "dict";
              if (obj1.optionsdic === t) {
                this.tableData.forEach((d) => {
                  const v =
                    val[i]?.filter((t1) => t1.value === d[obj1.prop])[0]
                      ?.name ?? "";
                  // 进行赋值
                  this.$set(d, propname, v);
                });
              }
            });
          });
        });
        resolve("ok");
      });
    },
    tableRowClassNames({ row, rowIndex }) {
      row.row_index = rowIndex;
      if (row.SHIPSTATUS === "04") {
        return "error-row";
      }
      const flag = this.tableRowClassName({ row, rowIndex });
      return flag;
    },
    // 获取当前表格选中的数据
    selectList() {
      if (this.list.length > 0) {
        const idlist = JSON.parse(JSON.stringify(this.list));
        return Promise.resolve(idlist);
      } else {
        this.$message({
          message: "请选择数据",
          type: "warning",
        });
        return new Promise(() => {}); // 中断promise链
      }
    },
    // 选择行
    selectRow(val, e) {
      this.list = val;
      if (this.options && this.options.tabletype === "radio") {
        if (val.length > 1) {
          this.$refs.mytable.clearSelection();
          this.$refs.mytable.toggleRowSelection(val.pop());
        }
      }
      this.$emit("selectRow", val);
    },
    // 选择表格中的数据弹出对话框
    async operation({ title, fun, type, tip, isavailablefun }) {
      const idlist = await this.selectList();
      // 是否可以提交
      // 是否可以删除
      // 是否可以撤回
      if (this.options.iszf) {
        for (const key in idlist) {
          const flag = idlist[key][this.options.iszf];
          if (isavailablefun && typeof isavailablefun === "function") {
            const f = isavailablefun(idlist[key], flag);
            if (f === false) {
              return false;
            }
          }
          if (type === "del" || type === "submit") {
            if (flag !== "01" && flag !== "04") {
              this.$message.error(
                type === "del"
                  ? "勾选中的数据，有不能删除的数据"
                  : "勾选中的数据，有不能提交的数据"
              );
              return false;
            }
          } else if (type === "withdraw") {
            if (flag !== "02") {
              this.$message.error("勾选中的数据，有不能撤回的数据");
              return false;
            }
          } else if (type === "approved" && flag !== "03") {
            // 如果type是approved 审核通过 ，并且flag！=03 03为审核通过，则提示
            this.$message.error(`勾选中的数据，有不能${tip}的数据`);
            return false;
          }
        }
      }

      this.$confirm(title)
        .then(async(_) => {
          fun && fun(idlist);
        })
        .catch((_) => {});
    },
    // 设置选中行
    setCurrentRow(obj) {
      this.$refs.mytable.setCurrentRow(obj);
    },
    // 当表格的当前行发生变化的时候会触发该事件，如果要高亮当前行，请打开表格的 highlight-current-row 属性
    CurrentChange(currentRow, oldCurrentRow) {
      this.$emit("currentChange", currentRow, oldCurrentRow);
    },
    // 是否展示编辑按钮
    isEditShow(value, row, index, btn) {
      // 如果是作废直接禁用
      if (value === "00") return false;
      const isEditStr = "02,03";
      if (btn) {
        // 如果是作废状态只展示查看按钮
        if (value === "05" && btn.label === "查看") {
          return true;
        }
        if (value === "05") {
          return false;
        } else {
          if (isEditStr.indexOf(value) !== -1 && btn.label === "编辑") {
            return false;
          }
          return true;
        }
      }
      if (isEditStr.indexOf(value) !== -1) {
        return false;
      }
      return true;
    },
    // execl导出
    execlExport({ list, title }) {
      import("@/vendor/Export2Excel").then((excel) => {
        // 需要引入vendor/Export2Excel插件
        // 列头
        const tHeader = this.columns.map((t) => t.label);
        // 标识列头名称 方便转换：如性别
        const filterVal = this.columns.map((t) => t.prop);
        // 调用js查询方法-无分页-根据条件查询方法
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: title,
          autoWidth: true,
          bookType: "xlsx",
        });
      });
    },
    // execl导出 转换格式
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
  },
};
</script>

<style lang="scss">
/* // 将全选项隐藏 */
.radio thead .el-table-column--selection .cell {
  display: none;
}
.radio {
  .el-checkbox__inner {
    border-radius: 50%;
  }
}
.operates {
  display: flex;
  justify-content: space-around;
}
.el-divider__text,
.el-link {
  font-weight: 500;
  font-size: 13px;
}
.el-table .error-row {
  background: #ff978f;
}
</style>
